import Vue from 'vue'
import VueRouter from 'vue-router'
import auth from '@/utils/token'
import { Message } from 'element-ui'
// import LoginPage from '@/views/login/LoginPage.vue'
// import Layout from '@/views/publish/Layout.vue'
// import HomePage from '@/views/home/HomePage.vue'
// import ArticlePage from '@/views/article/ArticlePage.vue'
// import PublishPage from '@/views/publish/PublishPage.vue'

// 按需加载
const LoginPage = () => import('@/views/login/LoginPage.vue')
/**
 * 动态导入发布布局组件
 *
 * 本函数使用了动态导入语法，按需加载'@/views/publish/Layout.vue'组件
 * 这种方式可以优化应用的加载性能，通过将组件分割成单独的代码块来延迟加载
 * 直到组件实际需要时才进行加载
 */
const Layout = () => import('@/views/publish/Layout.vue')
const HomePage = () => import('@/views/home/HomePage.vue')
const ArticlePage = () => import('@/views/article/ArticlePage.vue')
const PublishPage = () => import('@/views/publish/PublishPage.vue')
const MyPage = () => import('@/views/login/MyPage.vue')

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/login', component: LoginPage },
    {
      path: '/',
      component: Layout,
      children: [
        { path: '', component: HomePage },
        { path: '/article', component: ArticlePage },
        { path: '/publish/:id?', component: PublishPage },
        { path: '/my', component: MyPage }
      ]
    }
  ]
})

// 导航守卫
router.beforeEach((to, form, next) => {
  const token = auth.getToken()
  if (to.path !== '/login' && !token) {
    Message.error('登录信息已失效，请重新登录')
    return next('/login')
  }
  next()
})
// 导出路由实例
export default router
